package com.raise.drive.commons.web.springmvc.view;

import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletOutputStream;
import java.util.Map;

/**
 * @author Eugene Rozov
 */
public class PdfView implements View {

    public static final String PDF_BYTES_MODEL_KEY = "pdfBytes";

    public static final String FILE_NAME_MODEL_KEY = "fileName";
    private static final String CONTENT_TYPE = "application/pdf";

    public String getContentType() {
        return CONTENT_TYPE;
    }


    public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {

        byte[] data = (byte[]) model.get(PDF_BYTES_MODEL_KEY);
        String fileName = (String) model.get(FILE_NAME_MODEL_KEY);

        response.setContentType(CONTENT_TYPE);
        response.setContentLength(data.length);
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setHeader("Content-disposition", "inline; filename=\"" + fileName + '\"');

        ServletOutputStream out = response.getOutputStream();
        out.write(data);
        out.flush();
        out.close();
    }
}
